package com.flute.haflute.net;

import gnu.cajo.invoke.Remote;
import gnu.cajo.utils.ItemServer;

import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.flute.haflute.common.ClusterContext;

/**
 * 注册RMI端口，为RMI和CAJO等通信提供基础服务; 通常运行于服务器端
 */
public class RMINetService {
	private static RMINetService instance= new RMINetService();
	
	public static RMINetService getInstance() {
		return instance;
	}
	
	public RMINetService() {
		try {
			Registry registry = LocateRegistry.getRegistry("localhost", ClusterContext.getRMIPort());
			registry.list();
			System.out.println("RMI Registry found for port:" + ClusterContext.getRMIPort());
		} catch (final Exception e) {
			try {
				LocateRegistry.createRegistry(ClusterContext.getRMIPort());
				System.out.println("Register the registry server on port= " + ClusterContext.getRMIPort());
			} catch (final Exception ee) {
				ee.printStackTrace();
			}
		}
		//config CAJO
		Remote.config("0.0.0.0", ClusterContext.getRMIPort() - 1 , null, 0);
	}
	
	public void bindService(Object serviceObj, String serviceName) throws IOException {
		ItemServer.bind(serviceObj, serviceName);
	}
	
	public void shutdown() {
		Remote.shutdown();
	}
	
}
